package dict_list_service

import (
	"gorm.io/gorm"
	dld "pear-admin-layui-go/app/sys/dict_list/domain"
	fd "pear-admin-layui-go/framework/database"
)

func DictListCode(code string) []dld.DictListCodeResponse {
	var dls []dld.DictList
	fd.Db.Model(dld.DictList{}).Where("del_flag = false AND enable = true AND type_code = ?", code).Select("data_label", "data_value", "is_default").Find(&dls)
	dlcr := make([]dld.DictListCodeResponse, len(dls))
	for i, v := range dls {
		dlcr[i] = dld.DictListCodeResponse{
			DataLabel: v.DataLabel,
			DataValue: v.DataValue,
			IsDefault: v.IsDefault,
		}
	}
	return dlcr
}

func Enable(dler *dld.DictListEnableRequest) *gorm.DB {
	d := fd.Db.Model(dld.DictList{Id: dler.Id}).Select("enable", "update_time", "update_by", "update_name").Updates(dld.DictList{
		Enable:     dler.Enable,
		UpdateTime: dler.UpdateTime,
		UpdateBy:   dler.UpdateBy,
		UpdateName: dler.UpdateName,
	})
	return d
}

func EditPage(id int64) dld.DictList {
	var dl dld.DictList
	fd.Db.Select("id", "data_label", "data_value", "remark").First(&dl, id)
	return dl
}

func IsDefault(dler *dld.DictIsDefaultEnableRequest) *gorm.DB {
	d := fd.Db.Model(dld.DictList{Id: dler.Id}).Select("is_default", "update_time", "update_by", "update_name").Updates(dld.DictList{
		IsDefault:  dler.IsDefault,
		UpdateTime: dler.UpdateTime,
		UpdateBy:   dler.UpdateBy,
		UpdateName: dler.UpdateName,
	})
	return d
}

func Edit(dler *dld.DictListEditRequest) *gorm.DB {
	r := fd.Db.Model(dld.DictList{Id: dler.Id}).Updates(dld.DictList{
		DataLabel:  dler.DataLabel,
		DataValue:  dler.DataValue,
		Remark:     dler.Remark,
		UpdateTime: dler.UpdateTime,
		UpdateBy:   dler.UpdateBy,
		UpdateName: dler.UpdateName,
	})
	return r
}

func Save(dlsr *dld.DictListSaveRequest) (dld.DictList, error) {
	dl := dld.DictList{
		TypeCode:   dlsr.TypeCode,
		DataLabel:  dlsr.DataLabel,
		DataValue:  dlsr.DataValue,
		IsDefault:  dlsr.IsDefault,
		Enable:     dlsr.Enable,
		Remark:     dlsr.Remark,
		DelFlag:    false,
		CreateTime: dlsr.CreateTime,
		CreateBy:   dlsr.CreateBy,
		CreateName: dlsr.CreateName,
	}
	result := fd.Db.Create(&dl)
	return dl, result.Error
}

func Table(dlst *dld.DictListSearchTable) ([]dld.DictList, int64) {
	var count int64
	db := fd.Db.Model(dld.DictList{}).Where("type_code = ? AND del_flag = false", dlst.TypeCode)
	db.Count(&count)
	var dls []dld.DictList
	db.Select("id", "type_code", "is_default", "data_label", "data_value", "enable", "remark", "create_name",
		"create_time", "update_name", "update_time").Limit(dlst.Limit).Offset((dlst.Page - 1) * dlst.Limit).Find(&dls)
	return dls, count
}
